struct ListNode {
    int val;
    ListNode* next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode* next) : val(x), next(next) {}
};

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (head == nullptr || head->next == nullptr) {
            return head;
        }
        ListNode* pre = nullptr;
        ListNode* l = head;
        ListNode* r = head->next;
        while (r != nullptr) {
            if (l->val != r->val) {
                pre = l;
                l = l->next;
                r = r->next;
            }
            else {
                do {
                    r = r->next;
                } while (r != nullptr && r->val == l->val);
                if (r == nullptr) {
                    if (pre == nullptr) {
                        head = nullptr;
                    }
                    else {
                        pre->next = nullptr;
                    }
                }
                else {
                    l = r;
                    r = r->next;
                    if (pre == nullptr) {
                        head = l;
                    }
                    else {
                        pre->next = l;
                    }
                }
            }
        }
        return head;
    }
};